import { computed, effectScope, onScopeDispose, ref, toRefs, watch } from 'vue';
import { defineStore } from 'pinia';
import type { Socket } from 'socket.io-client';
import { io } from 'socket.io-client';
import { useAuthStore } from '../auth';

// 类型定义（与 ThemeStore 风格统一）
// 1. 拆分接口定义（替代 namespace）
export interface IOnlineUser {
  userId: string;
  username: string;
  isOnline: boolean;
  connectedAt: Date;
  clientId: string;
}
export interface SocketState {
  socket: Socket | null;
  isConnected: boolean;
  error: string | null;
  messages: SocketMessage[];
  currentRoom: string | null;
  // 在线用户列表
  onlineUsers: IOnlineUser[];
}

export interface SocketMessage {
  id?: string;
  content: string;
  sender: string;
  timestamp: Date;
  room?: string;
  read: boolean;
}

type SocketEvent = 'connect' | 'disconnect' | 'error' | 'newMessage' | 'roomMessage';

// 初始化默认状态（类似 initThemeSettings）
const initSocketState = (): SocketState => ({
  socket: null,
  isConnected: false,
  error: null,
  messages: [],
  currentRoom: null,
  onlineUsers: []
});

export const useSocketStore = defineStore('socket', () => {
  const scope = effectScope();
  const state = ref<SocketState>(initSocketState());

  const authStore = useAuthStore();

  // 计算属性（与 ThemeStore 风格统一）
  const isConnected = computed(() => state.value.isConnected);
  const error = computed(() => state.value.error);
  const messages = computed(() => state.value.messages);
  // const username = computed(() => state.value.username);
  const currentRoom = computed(() => state.value.currentRoom);
  const unreadCount = computed(() => state.value.messages.filter(msg => !msg.read).length);

  /** 初始化 Socket 连接 */
  const initSocket = (serverUrl: string = import.meta.env.VITE_SERVICE_BASE_URL || 'http://localhost:3000') => {
    const fullUrl = `${serverUrl}/chat`;
    // 已存在连接则先断开
    if (state.value.socket) {
      state.value.socket.disconnect();
    }

    /** 注册 Socket 事件监听（内部方法） */
    const registerEventListeners = () => {
      const socket = state.value.socket;
      if (!socket) return;

      // 连接成功
      socket.on('connect', () => {
        console.log('客户端连接成功，命名空间:', socket);
        state.value.isConnected = true;
        state.value.error = null;
      });

      // 连接断开
      socket.on('disconnect', (reason: string) => {
        state.value.isConnected = false;
        if (reason !== 'io client disconnect') {
          state.value.error = `连接断开，正在尝试重连...`;
        }
      });

      // 识别用户身份
      socket.emit('identify', {
        userId: authStore.userInfo.userId,
        username: authStore.userInfo.userName
      });

      // 监听身份识别结果
      socket.on('identified', data => {
        console.log('身份识别成功:', data.userInfo);
      });

      // 获取在线用户列表
      socket.emit('getOnlineUsers');

      // 监听在线用户更新
      socket.on('onlineUsersUpdate', data => {
        console.log('在线用户列表:', data.users);
        console.log('总在线人数:', data.count);
        state.value.onlineUsers = data.users;
      });

      // 监听用户上线
      socket.on('userOnline', user => {
        console.log('用户上线:', user.username);
      });

      // 监听用户离线
      socket.on('userOffline', user => {
        console.log('用户离线:', user.username);
      });

      // 连接错误
      socket.on('connect_error', (err: Error) => {
        state.value.error = `连接失败: ${err.message}`;
      });

      // 接收普通消息
      socket.on('newMessage', (payload: Omit<SocketMessage, 'read'>) => {
        console.log('newMessage', payload);
        state.value.messages.push({
          ...payload,
          timestamp: new Date(payload.timestamp),
          read: false
        });
      });

      // 接收房间消息
      socket.on('roomMessage', (payload: Omit<SocketMessage, 'read'> & { room: string }) => {
        state.value.messages.push({
          ...payload,
          timestamp: new Date(payload.timestamp),
          read: false
        });
      });
      // 监听私信消息
      socket.on('privateMessage', (payload: Omit<SocketMessage, 'read'> & { toUserId: string }) => {
        console.log('privateMessage', payload);
        // 私信消息处理逻辑
      });
    };
    // 创建 Socket 实例
    // 显式指定 socket 类型
    const socket: Socket = io(fullUrl, {
      path: '/socket.io',
      reconnection: true,
      reconnectionAttempts: 5,
      autoConnect: false
    });
    state.value.socket = socket;
    // 注册事件监听
    registerEventListeners();
  };

  /** 建立连接 */
  const connect = () => {
    if (state.value.socket && !state.value.isConnected) {
      state.value.socket.connect();
    }
  };

  /** 断开连接 */
  const disconnect = () => {
    if (state.value.socket && state.value.isConnected) {
      state.value.socket.disconnect();
      state.value.isConnected = false;
    }
  };

  /** 发送普通消息 */
  const sendMessage = (content: string) => {
    if (!state.value.socket || !state.value.isConnected) {
      state.value.error = '未建立连接，请先连接服务器';
      return false;
    }

    const payload = {
      message: content,
      username: authStore.userInfo.userName,
      timestamp: new Date().toISOString()
    };
    state.value.socket.emit('chatMessage', payload);
    return true;
  };

  /** 加入房间 */
  const joinRoom = (room: string) => {
    if (!state.value.socket || !state.value.isConnected) {
      state.value.error = '未建立连接，请先连接服务器';
      return false;
    }

    state.value.socket.emit('joinRoom', room);
    state.value.currentRoom = room;
    return true;
  };

  /** 发送房间消息 */
  const sendRoomMessage = (room: string, content: string) => {
    if (!state.value.socket || !state.value.isConnected) {
      state.value.error = '未建立连接，请先连接服务器';
      return false;
    }

    const payload = {
      room,
      content,
      sender: authStore.userInfo.userName,
      timestamp: new Date().toISOString()
    };

    state.value.socket.emit('roomMessage', payload);
    return true;
  };

  /** 标记消息为已读 */
  const markAsRead = (id: string) => {
    const msgIndex = state.value.messages.findIndex(msg => msg.id === id);
    if (msgIndex > -1) {
      state.value.messages[msgIndex].read = true;
    }
  };

  /** 重置状态 */
  const resetStore = () => {
    disconnect();
    state.value = initSocketState();
  };

  /** 注册自定义事件监听 */
  const onEvent = (event: SocketEvent, callback: (...args: any[]) => void) => {
    if (state.value.socket) {
      state.value.socket.on(event, callback);
    }
  };

  /** 移除事件监听 */
  const offEvent = (event: SocketEvent, callback: (...args: any[]) => void) => {
    if (state.value.socket) {
      state.value.socket.off(event, callback);
    }
  };

  // 发送私人消息
  const sendPrivateMessage = (toUserId: string, content: string): void => {
    if (!state.value.socket || !state.value.isConnected) {
      state.value.error = '未建立连接，请先连接服务器';
      return;
    }
    // 发送私信给指定用户
    state.value.socket.emit('privateMessage', {
      toUserId,
      message: content
    });
  };
  // 副作用管理（与 ThemeStore 保持一致）
  scope.run(() => {
    // 监听连接状态变化，持久化存储
    watch(
      isConnected,
      val => {
        if (val) {
          console.log('Socket 连接成功');
        } else {
          console.log('Socket 连接断开');
        }
      },
      { immediate: true }
    );

    // 监听消息变化，可用于通知逻辑
    watch(
      messages,
      newMessages => {
        if (newMessages.length > 0) {
          const lastMsg = newMessages[newMessages.length - 1];
          if (!lastMsg.read) {
            // 可添加消息通知逻辑
          }
        }
      },
      { deep: true }
    );

    // 页面刷新/关闭时断开连接
    window.addEventListener('beforeunload', () => {
      disconnect();
    });
  });

  // 清理副作用
  onScopeDispose(() => {
    scope.stop();
    disconnect();
  });

  // 暴露状态和方法（与 ThemeStore 风格统一）
  return {
    ...toRefs(state.value),
    isConnected,
    error,
    messages,
    // username,
    currentRoom,
    unreadCount,
    initSocket,
    connect,
    disconnect,
    sendMessage,
    joinRoom,
    sendRoomMessage,
    markAsRead,
    resetStore,
    onEvent,
    offEvent,
    sendPrivateMessage
  };
});
